<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>贪吃蛇游戏</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#4ade80',
                        secondary: '#ef4444',
                        dark: '#1e293b',
                        light: '#f8fafc'
                    }
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .game-container {
                @apply relative bg-dark rounded-lg overflow-hidden border-4 border-primary shadow-lg;
            }
            .game-info {
                @apply text-primary font-bold mb-4 flex justify-between items-center;
            }
            .control-btn {
                @apply bg-primary/20 hover:bg-primary/40 text-primary rounded-lg p-3 transition-all duration-200 active:scale-90;
            }
        }
    </style>
</head>
<body class="bg-gradient-to-br from-gray-900 to-gray-800 min-h-screen flex flex-col items-center justify-center p-4 text-light">
    <div class="max-w-md w-full mx-auto">
        <h1 class="text-[clamp(1.5rem,5vw,2rem)] text-primary text-center mb-6 font-bold tracking-wider">贪吃蛇游戏</h1>
        
        <div class="game-info">
            <div>分数: <span id="score" class="ml-2">0</span></div>
            <button id="startBtn" class="bg-primary text-dark px-4 py-2 rounded-lg font-bold hover:bg-primary/80 transition-all">
                <i class="fa fa-play mr-1"></i> 开始
            </button>
        </div>
        
        <!-- 游戏容器固定尺寸以确保兼容性 -->
        <div class="game-container w-full" style="height: 400px;">
            <canvas id="gameCanvas" class="w-full h-full"></canvas>
            
            <!-- 游戏结束遮罩 -->
            <div id="gameOver" class="absolute inset-0 bg-dark/80 flex flex-col items-center justify-center hidden">
                <h2 class="text-secondary text-2xl font-bold mb-4">游戏结束!</h2>
                <p class="mb-2">你的分数: <span id="finalScore">0</span></p>
                <button id="restartBtn" class="mt-4 bg-primary text-dark px-4 py-2 rounded-lg font-bold hover:bg-primary/80 transition-all">
                    再来一局
                </button>
            </div>
        </div>
        
        <!-- 移动设备控制按钮 -->
        <div class="mt-6 grid grid-cols-3 gap-2 md:hidden">
            <div class="col-start-2">
                <button id="upBtn" class="control-btn w-full">
                    <i class="fa fa-arrow-up text-xl"></i>
                </button>
            </div>
            <div class="col-start-1 row-start-2">
                <button id="leftBtn" class="control-btn w-full">
                    <i class="fa fa-arrow-left text-xl"></i>
                </button>
            </div>
            <div class="col-start-2 row-start-2">
                <button id="downBtn" class="control-btn w-full">
                    <i class="fa fa-arrow-down text-xl"></i>
                </button>
            </div>
            <div class="col-start-3 row-start-2">
                <button id="rightBtn" class="control-btn w-full">
                    <i class="fa fa-arrow-right text-xl"></i>
                </button>
            </div>
        </div>
        
        <div class="mt-6 text-sm text-gray-400">
            <p class="mb-2"><i class="fa fa-keyboard-o mr-1"></i> 控制: 方向键或屏幕按钮</p>
            <p><i class="fa fa-info-circle mr-1"></i> 吃掉红色食物增长分数和长度，撞到墙壁或自己则游戏结束</p>
        </div>
    </div>

    <script>
        // 获取画布和上下文
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        
        // 确保画布有正确的尺寸（修复主要问题）
        function setupCanvas() {
            const container = canvas.parentElement;
            // 设置画布的实际尺寸与显示尺寸一致
            canvas.width = container.clientWidth;
            canvas.height = container.clientHeight;
            
            // 确保网格大小为整数且合理
            gridSize = Math.max(10, Math.floor(Math.min(canvas.width, canvas.height) / 20));
        }
        
        // 游戏变量初始化
        let snake = [];
        let food = {};
        let gridSize;
        let direction = 'right';
        let nextDirection = 'right';
        let score = 0;
        let gameSpeed = 150;
        let gameInterval = null;
        let isGameRunning = false;
        
        // DOM 元素
        const scoreElement = document.getElementById('score');
        const startBtn = document.getElementById('startBtn');
        const restartBtn = document.getElementById('restartBtn');
        const gameOverElement = document.getElementById('gameOver');
        const finalScoreElement = document.getElementById('finalScore');
        const upBtn = document.getElementById('upBtn');
        const downBtn = document.getElementById('downBtn');
        const leftBtn = document.getElementById('leftBtn');
        const rightBtn = document.getElementById('rightBtn');
        
        // 初始化游戏
        function initGame() {
            // 确保画布设置正确
            setupCanvas();
            
            // 设置初始蛇位置（居中）
            const centerX = Math.floor(canvas.width / (2 * gridSize)) * gridSize;
            const centerY = Math.floor(canvas.height / (2 * gridSize)) * gridSize;
            
            snake = [
                { x: centerX, y: centerY },
                { x: centerX - gridSize, y: centerY },
                { x: centerX - gridSize * 2, y: centerY }
            ];
            
            // 初始方向向右
            direction = 'right';
            nextDirection = 'right';
            
            // 重置分数
            score = 0;
            scoreElement.textContent = score;
            
            // 生成食物
            generateFood();
            
            // 隐藏游戏结束界面
            gameOverElement.classList.add('hidden');
            
            // 初始绘制
            draw();
        }
        
        // 生成食物
        function generateFood() {
            // 确保食物不会出现在蛇身上
            let newFood;
            let onSnake;
            
            do {
                onSnake = false;
                newFood = {
                    x: Math.floor(Math.random() * (canvas.width / gridSize)) * gridSize,
                    y: Math.floor(Math.random() * (canvas.height / gridSize)) * gridSize
                };
                
                // 检查食物是否在蛇身上
                for (let segment of snake) {
                    if (segment.x === newFood.x && segment.y === newFood.y) {
                        onSnake = true;
                        break;
                    }
                }
            } while (onSnake);
            
            food = newFood;
        }
        
        // 绘制游戏
        function draw() {
            // 清空画布
            ctx.fillStyle = '#1e293b';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            
            // 绘制蛇
            snake.forEach((segment, index) => {
                // 蛇头颜色不同
                ctx.fillStyle = index === 0 ? '#22c55e' : '#4ade80';
                ctx.fillRect(segment.x, segment.y, gridSize - 1, gridSize - 1);
            });
            
            // 绘制食物
            ctx.fillStyle = '#ef4444';
            ctx.fillRect(food.x, food.y, gridSize - 1, gridSize - 1);
        }
        
        // 更新游戏状态
        function update() {
            // 确保游戏在运行中
            if (!isGameRunning) return;
            
            // 更新方向
            direction = nextDirection;
            
            // 获取蛇头位置
            const head = { x: snake[0].x, y: snake[0].y };
            
            // 根据方向移动蛇头
            switch (direction) {
                case 'up':
                    head.y -= gridSize;
                    break;
                case 'down':
                    head.y += gridSize;
                    break;
                case 'left':
                    head.x -= gridSize;
                    break;
                case 'right':
                    head.x += gridSize;
                    break;
            }
            
            // 检查是否撞墙
            if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height) {
                gameOver();
                return;
            }
            
            // 检查是否撞到自己
            for (let i = 0; i < snake.length; i++) {
                if (snake[i].x === head.x && snake[i].y === head.y) {
                    gameOver();
                    return;
                }
            }
            
            // 将新头部添加到蛇
            snake.unshift(head);
            
            // 检查是否吃到食物
            if (head.x === food.x && head.y === food.y) {
                // 增加分数
                score += 10;
                scoreElement.textContent = score;
                
                // 生成新食物
                generateFood();
                
                // 随着分数增加提高速度
                if (score % 50 === 0 && gameSpeed > 80) {
                    gameSpeed -= 10;
                    restartGameLoop();
                }
            } else {
                // 如果没吃到食物，移除尾部
                snake.pop();
            }
            
            // 绘制更新后的游戏
            draw();
        }
        
        // 重启游戏循环（用于速度调整）
        function restartGameLoop() {
            if (gameInterval) {
                clearInterval(gameInterval);
            }
            gameInterval = setInterval(update, gameSpeed);
        }
        
        // 开始/暂停游戏
        function toggleGame() {
            if (!isGameRunning) {
                // 开始游戏
                isGameRunning = true;
                restartGameLoop();
                startBtn.innerHTML = '<i class="fa fa-pause mr-1"></i> 暂停';
            } else {
                // 暂停游戏
                clearInterval(gameInterval);
                gameInterval = null;
                isGameRunning = false;
                startBtn.innerHTML = '<i class="fa fa-play mr-1"></i> 继续';
            }
        }
        
        // 游戏结束
        function gameOver() {
            clearInterval(gameInterval);
            gameInterval = null;
            isGameRunning = false;
            finalScoreElement.textContent = score;
            gameOverElement.classList.remove('hidden');
            startBtn.innerHTML = '<i class="fa fa-play mr-1"></i> 开始';
        }
        
        // 处理键盘控制
        function handleKeyPress(e) {
            // 防止蛇180度转向
            switch (e.key) {
                case 'ArrowUp':
                    if (direction !== 'down') {
                        nextDirection = 'up';
                    }
                    break;
                case 'ArrowDown':
                    if (direction !== 'up') {
                        nextDirection = 'down';
                    }
                    break;
                case 'ArrowLeft':
                    if (direction !== 'right') {
                        nextDirection = 'left';
                    }
                    break;
                case 'ArrowRight':
                    if (direction !== 'left') {
                        nextDirection = 'right';
                    }
                    break;
                case ' ': // 空格键控制开始/暂停
                    e.preventDefault();
                    toggleGame();
                    break;
            }
        }
        
        // 事件监听
        document.addEventListener('keydown', handleKeyPress);
        startBtn.addEventListener('click', toggleGame);
        restartBtn.addEventListener('click', () => {
            initGame();
            toggleGame();
        });
        
        // 移动设备控制
        upBtn.addEventListener('click', () => {
            if (direction !== 'down') {
                nextDirection = 'up';
            }
        });
        
        downBtn.addEventListener('click', () => {
            if (direction !== 'up') {
                nextDirection = 'down';
            }
        });
        
        leftBtn.addEventListener('click', () => {
            if (direction !== 'right') {
                nextDirection = 'left';
            }
        });
        
        rightBtn.addEventListener('click', () => {
            if (direction !== 'left') {
                nextDirection = 'right';
            }
        });
        
        // 窗口大小改变时重新设置画布
        window.addEventListener('resize', () => {
            const wasRunning = isGameRunning;
            if (wasRunning) {
                toggleGame();
            }
            initGame();
            if (wasRunning) {
                toggleGame();
            }
        });
        
        // 初始化游戏
        initGame();
    </script>
</body>
</html>
